/* eslint-disable */
var _ = require('lodash')
var request = require('../helpers/request')

function api(req, res, next) {
    req.api = async(path, method = 'GET', opts = {}) => {
        if (_.isObject(path)) {
            opts = _.merge(opts, path)
        }
        if (_.isObject(method)) {
            opts = _.merge(opts, method)
            method = 'GET'
        }
        if (!_.has(opts, 'method')) {
            opts.method = method
        }
        if (!opts.path) {
            opts.path = path
        }
        if (_.has(opts, 'body')) {
            opts.formData = opts.body
        }
        opts.headers = opts.headers || {}
        opts.headers['user-agent'] = req.headers['user-agent']
        return await request(opts)
    }
    next()
}
const installAPI = (app) => {
    app.use(api)
}

module.exports = installAPI